package com.rpj.stauy.controller;

import com.rpj.stauy.service.MyService;
import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.transport.McpTransport;
import dev.langchain4j.mcp.client.transport.stdio.StdioMcpTransport;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.service.AiServices;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping
public class MyController {

    @Resource
    private StreamingChatModel streamingChatModel;
    //http://localhost:9102/mcp/chat?question=北京明天天气
    @GetMapping("/mcp/chat")
    public Flux<String> chat(@RequestParam("question") String question){
        System.out.println("11111111111");
        //1构建Transport协议，连接百度地图mcp
        McpTransport transport = new StdioMcpTransport.Builder()
                .command(List.of("cmd", "/c", "npx", "-y", "@baidumap/mcp-server-baidu-map"))
                .environment(Map.of("BAIDU_MAP_API_KEY", System.getenv("BAIDU_MAP_API_KEY")))
                .build();

        //2构建client客户端
        DefaultMcpClient defaultMcpClient = new DefaultMcpClient.Builder()
                .transport(transport)
                .build();
        //3创建工具和原生的FunctionCalling类似
        McpToolProvider mcpToolProvider = McpToolProvider.builder().mcpClients(defaultMcpClient)
                .build();
        // 4.通过AiServices给我们自定义接口McpService构建实现类并将工具集和大模型赋值给AiService
        MyService myService = AiServices.builder(MyService.class)
                .streamingChatModel(streamingChatModel)
                .toolProvider(mcpToolProvider)
                .build();
        // 5.调用我们定义的HighApi接口,通过大模型对百度mcpserver调用
        Flux<String> stringFlux = myService.chat(question);
        System.out.println(stringFlux);
        stringFlux.doOnNext(response -> {
            System.out.println("MCP Response: " + response);
        }).doOnError(error -> {
            System.err.println("MCP Error: " + error.getMessage());
            error.printStackTrace();
        }).doOnComplete(() -> {
            System.out.println("MCP communication completed");
        });
        return stringFlux;
    }
}
